<!--
 * @FileDescription: 超级无敌table组件
 * @Author: XD
 * @Date: 10-15-2020
 * @LastEditors: 10-15-2020
 * @LastEditTime: 10-15-2020s
 -->

<!--
slot使用方法
<template v-slot:a="slotData">
    <Edit :data="slotData.data"></Edit>
</template>
<template v-slot:add>
    <Add></Add>
</template>
-->

<template>
    <div>


        <div class="right-select">
            <div class="right_base">

                <template v-for="(item, index) in this.privateConfig.header.search">
                    <!-- 下拉 搜索栏-->
                    <div class="private"
                         :key="index"
                         v-if="item.type == 'dropDown' || item.type == 'netDropDown'"
                    >
                        <p
                                class="p_base">

                            {{ item.label }}
                        </p>

                        <XDSelecter
                                class="dropdown"
                                v-model="item.value"
                                :type="item.type"
                                :list="item.list"
                        ></XDSelecter>
                    </div>

                    <!--  时间data 搜索框    -->
                    <div class="private" :key="index" v-if="item.type == 'datePicker'">
                        <p
                                class="p_base"

                        >
                            {{ item.label }}
                        </p>
                        <XDDatePicker v-model="item.value" type="date"></XDDatePicker>
                    </div>

                    <!--  时间datatime 搜索框 -->
                    <div class="private" :key="index" v-if="item.type == 'datePickerDateTime'">
                        <p
                                class="p_base"

                        >
                            {{ item.label }}
                        </p>
                        <XDDatePicker v-model="item.value" type="datetime"></XDDatePicker>
                    </div>

                    <!--输入 搜索框-->
                    <div class="private" :key="index" v-if="item.type == 'input'">
                        <p
                                class="p_base"

                        >
                            {{ item.label }}
                        </p>
                        <XDInput
                                v-model="item.value"
                                class="input"
                                :placeholder="item.placeholder"
                                :dataType="item.dataType"
                        ></XDInput>
                    </div>
                </template>

                <!--  重置栏-->
                <template v-if="privateConfig.header.search.length > 0">
                    <el-button
                            size="small"
                            class="inputButton"
                            type="primary"
                            @click="searchFunc"
                    >搜索</el-button
                    >
                    <el-button
                            style="color: #333"
                            size="small"
                            class="select"
                            @click="reset"
                    >重置</el-button
                    >
                </template>

                <!--  新增栏-->

                <template>
                    <div class="add_more">
                        <!--                   导出-->
                        <XDExport
                                v-if="this.privateConfig.header.export"
                                :config="this.privateConfig.header.export"
                        ></XDExport>
                        <el-button
                                size="small"
                                v-if="privateConfig.header.addButton"
                                class="select"
                                icon="el-icon-plus"
                                type="warning"
                                @click="showAddDialog"
                        >新增</el-button
                        >
                    </div>
                </template>

                <!--  新增插槽栏-->
                <template v-if="privateConfig.header.addButtonSlot">
                    <slot
                            class="select"
                            type="success"
                            :name="privateConfig.header.addButtonSlot"
                    ></slot>
                </template>
            </div>
        </div>

        <div class="table_ba">
            <div class="table_base">
                <el-table
                        :header-cell-style="{ background: '#F5F6F7', color: '#606266' }"
                        border
                        width="100%"
                        ref="table"
                        :data="tableData"
                        size="medium"
                        class="XDTable"
                        highlight-current-row
                        @current-change="handleCurrentChange"
                >
                    <!-- 普通文字-->
                    <template v-for="(item, index) in this.privateConfig.table">
                        <el-table-column
                                :key="index"
                                v-if="!item.type && !item.hidden"
                                :prop="item.prop"
                                :label="item.label"
                                align="center"
                                style="width: 100%; height: 1000px"
                        ></el-table-column>

                        <!-- index序号-->
                        <el-table-column
                                :key="index"
                                v-if="item.type == 'index'"
                                :label="item.label"
                                align="center"
                                style="width: 100%; height: 1000px"
                        >
                            <template slot-scope="scope">
                                <p>{{++scope.$index}}</p>
                            </template>
                        </el-table-column>

                        <!-- 下载按钮-->
                        <el-table-column
                                :key="item.prop"
                                v-if="item.type == 'download' && !item.hidden"
                                :prop="item.prop"
                                :label="item.label"
                                align="center"
                        >
                            <template slot-scope="scope">
                                <XDDownloader v-model="scope.row[item.prop]"></XDDownloader>
                            </template>
                        </el-table-column>

                        <!--普通按钮-->
                        <el-table-column
                                v-if="item.type === 'button' && !item.hidden"
                                :key="item.prop"
                                :prop="item.prop"
                                align="center"
                                :label="item.label"
                        >
                            <template slot-scope="scope">
                                <el-button
                                        size="small"
                                        type="primary"
                                        @click="item.callback(scope.row, item.prop)"
                                >{{ item.title }}</el-button
                                >
                            </template>
                        </el-table-column>

                        <!--    处理文字-->
                        <el-table-column
                                v-if="
                (item.type === 'dropDown' || item.type === 'radio') &&
                !item.hidden
              "
                                :key="item.prop"
                                :prop="item.prop"
                                align="center"
                                :label="item.label"
                        >
                            <template slot-scope="scope">
                <span
                >{{ dropDownLabel(item.list, scope.row[item.prop]) }}
                </span>
                            </template>
                        </el-table-column>

                        <!--   操作-->
                        <el-table-column
                                :key="item.index"
                                v-if="item.type == 'operation' && !item.hidden"
                                prop="isHandle"
                                :label="item.label"
                                align="center"
                                width="300"
                        >

                            <template slot-scope="scope">
                                <div style="display: flex; justify-content: center">

                                    <!--    查看-->
                                    <el-button
                                            size="small"
                                            type="primary"
                                            v-if="item.look"
                                            @click="look(scope.row)"
                                    >查看</el-button>

                                    <!--   编辑-->
                                    <el-button
                                            size="small"
                                            style="background-color: #39CE75; color: #fff"
                                            v-if="item.edit"
                                            @click="showEditDialog(scope.row)"
                                    >编辑</el-button>

                                    <!--   删除-->
                                    <el-button
                                            size="small"
                                            type="danger"
                                            v-if="item.delete"
                                            @click="beforeRemove(scope.row.id)"
                                    >删除</el-button>

                                    <!--                  跳转-->
                                    <el-button
                                            v-if="item.redirect"
                                            size="small"
                                            type="primary"
                                            @click="item.redirect.callback(scope.row, item.prop)"
                                    >{{ item.redirect.title }}</el-button>
                                </div>


                                <!--                            插槽-->
                                <div style="display: flex; justify-content: center">
                                    <template v-for="(item, index) in item.slotName">
                                        <div :key="index" style="margin-right: 10px">
                                            <slot :name="item" :data="scope.row"></slot>
                                        </div>
                                    </template>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>
        </div>

        <template v-if="this.privateConfig.footer.pagination">
            <div class="pagination">
                <el-pagination
                        background
                        layout="prev, pager, next, jumper,total"
                        :total="this.tableLength"
                        :page-size="10"
                        @current-change="currentPageChanged"
                        :current-page="page"
                        v-prevent-re-click
                ></el-pagination>
            </div>
        </template>


        <EleFormComp
                :config="privateConfig"
                :visibilityUpdate="visibilityUpdate"
                :title="title"
                :id="id"
                :disabled="formDisabled"
        >
            <div :slot="slotNames[0].slotName" slot-scope="slotData ">
                <slot :name="slotNames[0].slotName" :data="slotData.data"></slot>
            </div>
            <div :slot="slotNames[1].slotName" slot-scope="slotData">
                <slot :name="slotNames[1].slotName" :data="slotData.data"></slot>
            </div>
            <div :slot="slotNames[2].slotName" slot-scope="slotData">
                <slot :name="slotNames[2].slotName" :data="slotData.data"></slot>
            </div>
        </EleFormComp>


    </div>
</template>

<script>
    import { loadTableData, deleteTableData, deleteTableData1 } from "./request";
    import { typeJson } from "./config.js";
    import { downloadFile } from "./download";

    export default {
        name: "XDTable",
        props: ["config"],
        data() {
            return {
                visibilityUpdate: 0, // 窗口是否可见
                id: -1, // id
                title: "", // 标题
                formDisabled: "",
                send: {},
                privateConfig: {
                    header: {
                        breadcrumb: "",
                        addButton: true,
                        addButtonSlot: "",
                        search: [
                            {
                                type: "input",
                                prop: "",
                                placeholder: "",
                                value: "",
                                label: "",
                            },
                            {
                                type: "dropDown",
                                prop: "",
                                list: typeJson.deviceType,
                                value: "",
                                label: "",
                            },
                            {
                                type: "dateRangePicker",
                                value: "",
                                fromProp: "a",
                                toProp: "b",
                                label: "",
                            },
                            {
                                type: "dateTimeRangePicker",
                                value: "",
                                fromProp: "a",
                                toProp: "b",
                                label: "",
                            },
                        ],
                    },
                    footer: {
                        pagination: true,
                    },
                    table: [
                        {
                            label: "图片名字",
                            prop: "fileName",
                            value: "",
                            type: "download",
                            addEditType: "upload", //'timePicker'
                        },
                        {
                            label: "名誉名称",
                            prop: "honourName",
                            type: "function",
                            callback: (row, prop) => {
                                return row[prop];
                            },
                            value: "",
                            //addEditType: 'upload',
                            list: typeJson.sex,
                        },
                        {
                            label: "颁发机构",
                            prop: "giveDep",
                            value: "",
                            addEditType: "upload",
                        },
                        {
                            label: "操作",
                            prop: "", // 传数据的时候 忽略
                            type: "operation",
                            addEditHidden: true,
                            edit: true,
                            delete: true,
                            look: true,
                        },
                    ],
                    update: null,
                    delete: null,
                    insert: null,
                    select: null,
                },

                // 数据一共长度
                tableLength: 0,
                page: 1,
                tableData: [],
            };
        },
        computed: {
            slotNames: function () {
                let temp = [];
                for (let i = 0; i < this.privateConfig.table.length; i++) {
                    if (this.privateConfig.table[i].addEditType == "slot") {
                        temp.push(this.privateConfig.table[i]);
                    }
                }
                while (temp.length < 3) {
                    temp.push({ slotName: "" });
                }
                return temp;
            },
        },
        created() {
            this.initConfig();
            this.selectFunc();
        },
        mounted() {
            this.selectFunc();
        },
        methods: {
            // 选择table 传 选中后的数据和搜索条件
            handleCurrentChange(val) {
                let s = this.privateConfig.header.search;
                let temp = {};
                for (let i = 0; i < s.length; i++) {
                    temp[s[i].prop] = s[i].value;
                }
                this.$emit("handleCurrentChange", val, temp);
            },
            // 重置
            reset() {
                this.send = {};
                for (var i = 0; i < this.privateConfig.header.search.length; i++) {
                    this.privateConfig.header.search[i].value = "";
                }
                this.selectFunc()
            },

            // 搜索处理
            searchFunc() {
                let s = this.privateConfig.header.search;
                for (let i = 0; i < s.length; i++) {
                    this.send[s[i].prop] = s[i].value;
                }
                this.selectFunc()
            },

            // 分页处理
            currentPageChanged(val) {
                this.send.page = val;
                this.page = val;
                this.selectFunc()
            },

            // 处理下拉框显示文字
            dropDownLabel(list, val) {
                if (!list) return;
                for (var i = 0; i < list.length; i++) {
                    if (list[i].value === val) return list[i].label;
                }
                return "";
            },

            // 初始化配置项
            initConfig() {
                console.log(this.config)
                let configData = this.config;
                let keys = Object.keys(this.privateConfig);
                for (let key in configData) {
                    if (keys.includes(key)) {
                        this.privateConfig[key] = configData[key];
                    }
                }

                let page = this.getQueryVariable("page");
                if (page) this.page = parseInt(page);
            },

            // 获取参数
            getQueryVariable(variable) {
                let href = window.location.href;
                let query = href.substring(href.indexOf("?") + 1);
                let vars = query.split("&");
                for (var i = 0; i < vars.length; i++) {
                    let pair = vars[i].split("=");
                    if (pair[0] == variable) {
                        return pair[1];
                    }
                }
                return false;
            },

            // 查询
            selectFunc() {
                let searchData = {}
                let requestJson = this.privateConfig.select;
                if (requestJson.mineId) {
                    searchData.mineId = this.$store.state.mineId;
                }
                if (requestJson.companyId) {
                    searchData.companyId = this.$store.state.companyId;
                }
                if (requestJson.params) {
                    Object.assign(searchData, searchData, requestJson.params);
                }
                if (this.send) {
                    Object.assign(searchData, searchData, this.send);
                }
                requestJson.data = searchData;

                requestJson.currentPage = this.page;
                requestJson.pageSize = 10;
                loadTableData(requestJson)
                    .then((response) => {
                        let success = response.success;
                        if (!success) {
                            this.onFailed(response.msg);
                        } else {
                            if (response.data.list) {
                                this.tableData = response.data.list;
                            } else {
                                this.tableData = response.data;
                            }
                            this.tableLength = response.data.total;
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },

            //值复制
            clone(obj) {
                //判断是对象，就进行循环复制
                if (typeof obj === "object" && typeof obj !== "null") {
                    // 区分是数组还是对象，创建空的数组或对象
                    var o =
                        Object.prototype.toString.call(obj).slice(8, -1) === "Array"
                            ? []
                            : {};
                    for (var k in obj) {
                        // 如果属性对应的值为对象，则递归复制
                        if (typeof obj[k] === "object" && typeof obj[k] !== "null") {
                            o[k] = clone(obj[k]);
                        } else {
                            o[k] = obj[k];
                        }
                    }
                } else {
                    //不为对象，直接把值返回
                    return obj;
                }
                return o;
            },

            // 删除
            deleteFunc(id) {
                console.log(id);
                let requestJson = this.privateConfig.delete;
                requestJson.id = id;
                if (requestJson.params) {
                    requestJson.data = requestJson.params
                }
                //接口1
                deleteTableData(requestJson)
                    .then((response) => {
                        let res = response.msg;
                        if (res == "success") {
                            this.onSuccess("删除成功！");
                            this.selectFunc();
                        }
                    })
                    .catch((error) => {
                        //尝试接口2
                        deleteTableData1(requestJson)
                            .then((response) => {
                                let res = response.msg;
                                if (res == "success") {
                                    this.onSuccess("删除成功！");
                                    this.selectFunc();
                                } else {
                                    this.onFailed(res);
                                }
                            })
                            .catch((error) => {
                                console.log(error);
                                this.onFailed("删除失败！");
                            });
                    });
            },

            //成功msg
            onSuccess(message) {
                this.$message({
                    message: message || "成功",
                    type: "success",
                });
            },
            //失败msg
            onFailed(message) {
                this.$message({
                    message: message || "失败",
                    type: "error",
                });
            },

            //显示增加dialog
            showAddDialog() {
                let t = this.privateConfig.table;
                for (var i = 0; i < t.length; i++) {
                    t[i].value = "";
                }
                this.title = "新增";
                this.id = -1;
                this.visibilityUpdate += 1;
                this.formDisabled = false;
            },

            //显示编辑dialog
            showEditDialog(row) {
                let t = this.privateConfig.table;
                for (var i = 0; i < t.length; i++) {
                    for (let r of Object.keys(row)) {
                        if (r == t[i].prop) {
                            t[i].value = row[r];
                        }
                    }
                }
                this.id = row.id;
                this.title = "编辑";
                this.visibilityUpdate += 1;
                this.formDisabled = false;
            },

            // 查看dialog
            look(row) {
                let t = this.privateConfig.table;
                for (var i = 0; i < t.length; i++) {
                    for (let r of Object.keys(row)) {
                        if (r == t[i].prop) {
                            t[i].value = row[r];
                        }
                    }
                }
                this.title = "查看";
                this.visibilityUpdate += 1;
                this.formDisabled = true;
            },

            // 删除之前
            beforeRemove(id) {
                console.log(id);
                this.$confirm("此操作将永久删除该记录, 是否继续??", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.deleteFunc(id);
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            },
        },

        components: {},
    };
</script>

<style scoped lang="scss">
    .inputButton {
        margin-left: 10px;
    }

    .title-bareads {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .breadcrumbs {
            cursor: pointer;
            width: 100%;
            height: 65px;
            background-color: #fff;
            padding-left: 40px;
            display: flex;
            align-items: center;
            font-size: 20px;
            font-family: Source Han Sans CN;
            font-weight: 400;
            color: #757C91;
            margin-bottom: 12px;
            .goto {
                margin-right: 20px;
            }
            .heto {
                margin-left: 20px;
            }
            .span_an {
                width: 1px;
                height: 18px;
                background: #A5AAB9;
            }
        }
    }

    .right-select {
        width: 100%;

        padding: 0 12px;
        margin-bottom: 12px;
        position: relative;
        .right_base {
            width: 100%;
            background-color: #fff;
            display: flex;
            align-items: center;
            .private{
                height: 100%;
                display: flex;
                align-items: center;
                .p_base {
                    font-size: 16px;
                    color: #333;
                    font-family: Source Han Sans CN;
                    font-weight: 400;
                    margin-left: 20px;
                    margin-right: 10px;
                    white-space: nowrap;
                }

            }

            .add_more {
                display: flex;
            }
            .input {
                width: 180px;
                margin-right: 20px;
            }

            .dateRangePicker {
                margin-right: 20px;
                margin-bottom: 20px;
                width: 360px;
            }
            p {
                line-height: 38px;
            }
        }
    }
    .table_ba {
        padding: 0 12px;
        width: 100%;
        .table_base {
            padding-left: 20px;
            padding-right: 20px;
            background-color: #fff;
        }
    }
    .pagination {
        bottom: 30px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 20px;
    }

    :deep(.el-buttom--success) {
        color: #FFF;
        background-color: #39CE75;
        border-color: #39CE75;
    }
</style>




